package part11singleton;

/**
 * @description: 线程安全的懒汉模式，且避免了指令重排问题
 * 问题：会被反射破坏
 * @author: zhang hang
 * @date: 2024/3/24 14:17.
 * @version: 1.0
 */
public class SingletonTest04 {

    private SingletonTest04() {
        System.out.println(Thread.currentThread().getName() + "starting");
    }

    private static volatile SingletonTest04 instance;

    public static SingletonTest04 getInstance() {
        if (instance == null) {
            synchronized (SingletonTest04.class) {
                if (instance == null) {
                    instance = new SingletonTest04();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                SingletonTest04.getInstance();
            }).start();
        }
    }

}
